package com.warframe.activity;

import com.tools.HibernateUtils;
import com.tools.StringContent;
import com.warframe.entity.activity.Award;
import com.warframe.entity.database.StringContentEO;
import com.warframe.entity.message.Message;
import com.warframe.message.Executor;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.sqlite.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 读取奖品列表，包装奖品列表
 * 过滤群名片
 * 随机抽取奖品
 */
public class Activity implements Runnable {

	private final static String sql = "select * from StringContent where type = 'AWARD'";
	private final static String strStart = "恭喜 [CQ:at,qq=FROMQQ] 同学抽中 [";
//	private final static String strEnd =

	private final static String msg = "恭喜 [CQ:at,qq=FROMQQ] 同学抽中 BANTIME 秒禁言套餐！";
	private Message message;

	public Activity(Message message) {
		this.message = message;
	}

	public Activity() {
	}

	@Override
	public void run() {
		Collections.shuffle(Executor.activityAward);// FIXME: 2018/12/25 debug出错在这
		int index = 0;
		if (Executor.activityAward.size() > 0) {
			Award award = Executor.activityAward.get(index);
			Executor.activityAward.remove(index);
			if (award != null && award.getStrEnd() != null && award.getStrEnd().length() > 0) {
				Random random = new Random();
				Integer banTime = random.nextInt(180) + 1;
				Executor.getCQ().setGroupBan(message.getGroupId(), message.getFromQQ(), banTime);
				message.setSign(StringContent.SENDGROUP);
				message.setMsg(msg.replace("FROMQQ", message.getFromQQ().toString()).replace("BANTIME", banTime.toString()));
				Executor.getInstance().pushMsg(message);
			} else {
				message.setSign(StringContent.SENDGROUP);
				message.setMsg(award.toString().replace("FROMQQ", message.getFromQQ().toString()));
				StringContent.AWARDMAP.put(message.getFromQQ(),
						award.toString().replace("[CQ:at,qq=FROMQQ]",
						StringContent.GROUPMEMBERLIST.get(message.getGroupId()).get(message.getFromQQ()).getCard()));
				Executor.getInstance().pushMsg(message);
			}
		}
	}

	public List<Award> initAwardList() {
		Session session = HibernateUtils.getSessionFactory().openSession();
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		List<StringContentEO> EOList = sqlQuery.addEntity(StringContentEO.class).list();
		List<Award> awardList = new ArrayList<>();
		for (StringContentEO eachEO : EOList) {
			for (int i = 0; i < Integer.valueOf(eachEO.getKey()); i++) {
				if ("BANTIME".equals(eachEO.getValue())) {
					Award award = new Award(strStart, eachEO.getValue(), "] 秒禁言套餐！");
					awardList.add(award);
				} else {
					Award award = new Award(strStart, eachEO.getValue(), "");
					awardList.add(award);
				}
			}
		}
		return awardList;
	}

}
